package com.itheima.interceptor;

import com.itheima.utilis.CurrentHolder;
import com.itheima.utilis.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、获取请求头中的令牌
        String jwt = request.getHeader("token");
        if (jwt == null) {
            log.info("请求头中没有token");
            //没有携带令牌，拦截请求，封装错误结果
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);//401
            return false;
        }

        //2、解析令牌，判断令牌是否正确
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            //令牌不正确，拦截请求，封装错误结果
            log.info("令牌不正确，拦截请求！");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);//401
            return false;
        }

        //3、令牌正确，放行
        log.info("令牌正确，放行！");

        String jwtToken = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(jwtToken);
        Integer id =(Integer)claims.get("id");

        CurrentHolder.setCurrentId(id);
        return true;
    }
}
